package com.openingedu.mba.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.util.Log;

import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.openingedu.mba.entity.PaperVO;
import com.openingedu.mba.entity.QuestionOptionVO;
import com.openingedu.mba.entity.QuestionSeckillVO;
import com.openingedu.mba.entity.QuestionSolutionVO;
import com.openingedu.mba.entity.QuestionVO;
import com.openingedu.mba.http.HttpHandler;
import com.openingedu.mba.http.RequestParams;
import com.openingedu.mba.persist.DataHelper;
import com.openingedu.mba.persist.DbPaper;
import com.openingedu.mba.persist.DbPaperQuestion;
import com.openingedu.mba.persist.DbQuestion;
import com.openingedu.mba.persist.DbQuestionOption;
import com.openingedu.mba.persist.DbQuestionSeckill;
import com.openingedu.mba.persist.DbQuestionSolution;
import com.openingedu.mba.util.DESEncrypt;
import com.openingedu.mba.util.DeviceUtil;
import com.openingedu.mba.util.GsonUtil;
import com.openingedu.mba.util.MD5;

public class PaperService extends HttpService {

	private static final String TAG = PaperService.class.getSimpleName();

	/**
	 * 查询逻辑试题
	 * @param context 上下文
	 * @param handler 返回处理
	 */
	public synchronized void loadLogicPaper(Context context, HttpHandler handler) {
		// TODO getProfile from Profile
		String androidID = DeviceUtil.getAndroidID(context);
		Log.i("-----", "androidID=" + androidID);
		String hexRandom = DESEncrypt.createDESKey(6);
		String md5Key = hexRandom + MD5.encryptHex(hexRandom + "" + androidID);
		RequestParams params = new RequestParams();
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("signID", "200");
		// TODO deviceID
		reqMap.put("deviceID", 1);
		reqMap.put("secureKey", md5Key);
		params.put("req", GsonUtil.otj(reqMap));
		postRequest(params, handler);
	} 
	
	/**
	 * 取得购买试卷订单号
	 */
	public synchronized void getOrderIDForPaper(Context context, HttpHandler handler, Integer paperID) {
		// TODO getProfile from Profile
		String androidID = DeviceUtil.getAndroidID(context);
		Log.i("-----", "androidID=" + androidID);
		String hexRandom = DESEncrypt.createDESKey(6);
		String md5Key = hexRandom + MD5.encryptHex(hexRandom + "" + androidID);
		RequestParams params = new RequestParams();
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("signID", "301");
		// TODO deviceID
		reqMap.put("deviceID", 1);
		reqMap.put("paperID", paperID);
		reqMap.put("secureKey", md5Key);
		params.put("req", GsonUtil.otj(reqMap));
		postRequest(params, handler);
	}
	
	/**
	 * 下载试题
	 */
	public synchronized void downloadPaper(Context context, HttpHandler handler, Integer paperID) {
		String androidID = DeviceUtil.getAndroidID(context);
		String hexRandom = DESEncrypt.createDESKey(6);
		String md5Key = hexRandom + MD5.encryptHex(hexRandom + "" + androidID);
		RequestParams params = new RequestParams();
		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("signID", "201");
		// TODO deviceID
		reqMap.put("deviceID", 1);
		reqMap.put("paperID", paperID);
		reqMap.put("secureKey", md5Key);
		params.put("req", GsonUtil.otj(reqMap));
		
		StringBuffer buf = new StringBuffer();
		buf.append("signID=" + "201");
		buf.append(",deviceID=1");
		buf.append(",paperID=" + paperID);
		buf.append(",secureKey=" + md5Key);
		Log.i(TAG, "http params:" + buf.toString());
		postRequest(params, handler);
	}
	
	/**
	 * 保存试卷到数据库
	 */
	public synchronized boolean persistPaper(Context context, DataHelper dataHelper, PaperVO paper, List<QuestionVO> questionList) {
		try {
			DbPaper dbPaper = null;
			List<DbPaper> dbPaperList = dataHelper.getDbPaperDao().queryForEq("paperID", paper.getPaperID());
			// 试卷已经存在，修改试卷
			if (dbPaperList != null && dbPaperList.size() > 0) {
				dbPaper = dbPaperList.get(0);
				setPaperProperties(dbPaper, paper);
				// 修改试卷内容
				dataHelper.getDbPaperDao().update(dbPaper);
				Log.i("----", "update paper, title=" + paper.getPaperTitle());
			}
			// 试卷不存在，新建试卷
			else {
				dbPaper = new DbPaper();
				setPaperProperties(dbPaper, paper);
				// 保存试卷内容
				dataHelper.getDbPaperDao().create(dbPaper);
				Log.i("----", "create paper, title=" + paper.getPaperTitle());
			}
			
			List<Integer> questionIDs = new ArrayList<Integer>();
			// 遍历试题列表
			for (QuestionVO question : questionList) {
				DbQuestion dbQuestion = null;
				List<DbQuestion> questions = dataHelper.getDbQuestionDao().queryForEq("questionID", question.getId());
				// 已有试题
				if (questions != null && questions.size() > 0) {
					dbQuestion = questions.get(0);
					setQuestionProperties(dbQuestion, question);
					dataHelper.getDbQuestionDao().update(dbQuestion);
					Log.i("----", "update questionID=" + question.getId() + ", title=" + question.getQuestionTitle());
				}
				// 新试题
				else {
					dbQuestion = new DbQuestion();
					setQuestionProperties(dbQuestion, question);
					dataHelper.getDbQuestionDao().create(dbQuestion);
					Log.i("----", "create questionID=" + question.getId() + ", title=" + question.getQuestionTitle());
				}
				// TODO 删除相关选项
				// 遍历试题选项
				List<QuestionOptionVO> options = question.getQuestionOptions();
				for (QuestionOptionVO questionOption : options) {
					DbQuestionOption dbQuestionOption = null;
					List<DbQuestionOption> questionOptions = dataHelper.getDbQuestionOptionDao().queryForEq("optionID", questionOption.getId());
					if (questionOptions!=null && questionOptions.size() > 0) {
						dbQuestionOption = questionOptions.get(0);
						setOptionProperties(dbQuestion, dbQuestionOption, questionOption);
						dataHelper.getDbQuestionOptionDao().update(dbQuestionOption);
					}
					else {
						dbQuestionOption = new DbQuestionOption();
						setOptionProperties(dbQuestion, dbQuestionOption, questionOption);
						dataHelper.getDbQuestionOptionDao().create(dbQuestionOption);
					}
				}
				// TODO 删除相关解题方法
				// 遍历试题解题方法
				List<QuestionSolutionVO> solutions = question.getQuestionSolutions();
				for (QuestionSolutionVO questionSolution : solutions) {
					DbQuestionSolution dbQuestionSolution = null;
					List<DbQuestionSolution> questionSolutions = dataHelper.getDbQuestionSolutionDao().queryForEq("id", questionSolution.getId());
					if (questionSolutions!=null && questionSolutions.size() > 0) {
						dbQuestionSolution = questionSolutions.get(0);
						setSolutionProperties(dbQuestion, dbQuestionSolution, questionSolution);
						dataHelper.getDbQuestionSolutionDao().update(dbQuestionSolution);
					}
					else {
						dbQuestionSolution = new DbQuestionSolution();
						setSolutionProperties(dbQuestion, dbQuestionSolution, questionSolution);
						dataHelper.getDbQuestionSolutionDao().create(dbQuestionSolution);
					}
				}
				// TODO 删除相关解题方法
				// 遍历试题秒杀技巧
				List<QuestionSeckillVO> seckills = question.getQuestionSeckills();
				for (QuestionSeckillVO questionSeckill : seckills) {
					DbQuestionSeckill dbQuestionSeckill = null;
					List<DbQuestionSeckill> questionSeckills = dataHelper.getDbQuestionSeckillDao().queryForEq("id", questionSeckill.getId());
					if (questionSeckills!=null && questionSeckills.size() > 0) {
						dbQuestionSeckill = questionSeckills.get(0);
						setSeckillProperties(dbQuestion, dbQuestionSeckill, questionSeckill);
						dataHelper.getDbQuestionSeckillDao().update(dbQuestionSeckill);
					}
					else {
						dbQuestionSeckill = new DbQuestionSeckill();
						setSeckillProperties(dbQuestion, dbQuestionSeckill, questionSeckill);
						dataHelper.getDbQuestionSeckillDao().create(dbQuestionSeckill);
					}
				}
				
				// 保存试题与试卷关系
				questionIDs.add(dbQuestion.getQuestionID());
				Log.i("paperService", "qustionID=" + dbQuestion.getQuestionID());
			}
			
			Integer paperID = dbPaper.getPaperID();
			List<DbPaperQuestion> paperQuestionList = dataHelper.getDbPaperQuestionDao().queryForEq("paperID", paperID);
			if (paperQuestionList != null && paperQuestionList.size() > 0) {
				dataHelper.getDbPaperQuestionDao().delete(paperQuestionList);
				Log.i(TAG, "remove paper question map. paperID=" + paperID);
			}
			
			for (Integer questionID : questionIDs) {
				DbPaperQuestion paperQuestion = new DbPaperQuestion();
				paperQuestion.setPaper(dbPaper);
				paperQuestion.setQuestionID(questionID);
				dataHelper.getDbPaperQuestionDao().create(paperQuestion);
				Log.i(TAG, "add paper question to map table. paperID=" + paperID + ", questionID=" + questionID);
			}
			return true;
		}
		catch (SQLException e) {
			e.printStackTrace();
			Log.e("----", "persist Paper error." + e.getMessage(), e);
		}
		return false;
	}
	
	/**
	 * 设置秒杀属性
	 * @param dbQuestion
	 * @param dbQuestionSeckill
	 * @param questionSeckill
	 */
	private void setSeckillProperties(DbQuestion dbQuestion,
			DbQuestionSeckill dbQuestionSeckill,
			QuestionSeckillVO questionSeckill) {
		dbQuestionSeckill.setQuestion(dbQuestion);
		dbQuestionSeckill.setSeckillContent(questionSeckill.getSeckillContent());
	}

	/**
	 * 设置解析属性
	 * @param dbQuestion
	 * @param dbQuestionSolution
	 * @param questionSolution
	 */
	private void setSolutionProperties(DbQuestion dbQuestion,
			DbQuestionSolution dbQuestionSolution,
			QuestionSolutionVO questionSolution) {
		dbQuestionSolution.setQuestion(dbQuestion);
		dbQuestionSolution.setSolutionContent(questionSolution.getSolutionContent());
	}

	/**
	 * 根据QuestionOptionVO设置DbQuestionOption属性
	 */
	private void setOptionProperties(DbQuestion dbQuestion,
			DbQuestionOption dbQuestionOption, QuestionOptionVO questionOption) {
		dbQuestionOption.setOptionID(questionOption.getId());
		dbQuestionOption.setQuestion(dbQuestion);
		dbQuestionOption.setOptionContent(questionOption.getOptionContent());
		dbQuestionOption.setOptionCorrect(questionOption.getOptionCorrect());
	}

	/**
	 * 根据QuestionVO设置DbQuestion属性
	 */
	private void setQuestionProperties(DbQuestion dbQuestion,
			QuestionVO question) {
		dbQuestion.setQuestionID(question.getId());
		dbQuestion.setQuestionIndex(question.getQuestionIndex());
		dbQuestion.setQuestionSerial(question.getQuestionSerial());
		dbQuestion.setQuestionStatus(question.getQuestionStatus());
		dbQuestion.setQuestionSummary(question.getQuestionSummary());
		dbQuestion.setQuestionTag(question.getQuestionTag());
		dbQuestion.setQuestionTitle(question.getQuestionTitle());
		dbQuestion.setQuestionType(question.getQuestionType());
		dbQuestion.setQuestionImage(question.getQuestionImage());
		dbQuestion.setQuestionImage1(question.getQuestionImage1());
		dbQuestion.setQuestionImage2(question.getQuestionImage2());
	}

	/**
	 * 根据PaperVO设置DbPaper属性
	 */
	private void setPaperProperties(DbPaper dbPaper, PaperVO paper) {
		dbPaper.setPaperID(paper.getPaperID());
		dbPaper.setPaperDesc(paper.getPaperDesc());
		dbPaper.setPaperPrice(paper.getPaperPrice());
		dbPaper.setPaperSerial(paper.getPaperSerial());
		dbPaper.setPaperStatus(paper.getPaperStatus());
		dbPaper.setPaperTitle(paper.getPaperTitle());
		dbPaper.setPaperType(paper.getPaperType());
		dbPaper.setPaperTypeTitle(paper.getPaperTypeTitle());
		dbPaper.setPaperVersion(paper.getPaperVersion());
	}

	public PaperVO findPaper(Context context, Integer paperID) {
		DataHelper dataHelper = new DataHelper(context);
		List<DbPaper> paperList = null;
		try {
			QueryBuilder<DbPaper, Long> queryBuilder = dataHelper.getDbPaperDao().queryBuilder();
			Where<DbPaper, Long> where = queryBuilder.where();
			where.eq("paperID", paperID);
			paperList = queryBuilder.query();
			if (paperList!=null && paperList.size() > 0) {
				return new PaperVO(paperList.get(0));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}
